#!/usr/bin/env bash
if [ "${BASH_SOURCE-}" = "$0" ]; then
    echo "You must source this script: \$ source $0" >&2
    exit 1
fi

deactivate () {
    # reset old environment variables
    # ! [ -z ${VAR+_} ] returns true if VAR is declared at all
    if ! [ -z "${_OLD_ENVIRONMENT_PATH:+_}" ] ; then
        PATH="$_OLD_ENVIRONMENT_PATH"
        export PATH
        unset _OLD_ENVIRONMENT_PATH
    fi
    if ! [ -z "${_OLD_ENVIRONMENT_PYTHONHOME+_}" ] ; then
        PYTHONHOME="$_OLD_ENVIRONMENT_PYTHONHOME"
        export PYTHONHOME
        unset _OLD_ENVIRONMENT_PYTHONHOME
    fi

    # This should detect bash and zsh, which have a hash command that must
    # be called to get it to forget past commands.  Without forgetting
    # past commands the $PATH changes we made may not be respected
    if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then
        hash -r 2>/dev/null
    fi

    if ! [ -z "${_OLD_ENVIRONMENT_PS1+_}" ] ; then
        PS1="$_OLD_ENVIRONMENT_PS1"
        export PS1
        unset _OLD_ENVIRONMENT_PS1
    fi

    unset VIRTUAL_ENV
    unset VERILATOR_ROOT
    unset GHDL_PREFIX
    if [ ! "${1-}" = "nondestructive" ] ; then
    # Self destruct!
        unset -f deactivate
    fi
}

# unset irrelevant variables
deactivate nondestructive

if [ -n "${ZSH_VERSION-}" ] ; then
    release_current_dir="$(dirname "$0")"
else
    release_current_dir="$(dirname "${BASH_SOURCE[0]}")"
fi

if [[ "$(uname)" == "Darwin" ]]; then
    release_topdir_abs="$("$release_current_dir"/libexec/realpath "$release_current_dir")"
else
    release_topdir_abs="$(realpath "$release_current_dir")"
fi

export VIRTUAL_ENV='___BRANDING___'

_OLD_ENVIRONMENT_PATH="$PATH"
PATH="$release_topdir_abs/bin:$release_topdir_abs/py3bin:$PATH"
export PATH

# unset PYTHONHOME if set
if ! [ -z "${PYTHONHOME+_}" ] ; then
    _OLD_ENVIRONMENT_PYTHONHOME="$PYTHONHOME"
    unset PYTHONHOME
fi

_OLD_ENVIRONMENT_PS1="${PS1-}"
if [ -n "${ZSH_VERSION-}" ] ; then
    autoload -U colors && colors
    PS1="%{$fg[magenta]%}(${VIRTUAL_ENV})%{$reset_color%} ${PS1-}"
else
    PS1="\[\033[1;35m\]\342\246\227${VIRTUAL_ENV}\342\246\230\[\033[0m\] ${PS1-}"
fi
export PS1

export VERILATOR_ROOT="$release_topdir_abs/share/verilator"
export GHDL_PREFIX="$release_topdir_abs/lib/ghdl"

# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands.  Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then
    hash -r 2>/dev/null
fi
